package cfdt.tools.json;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;

import java.util.Map;
import java.util.TreeMap;

/**
 * 使用HUTOOL-JSON封装的工具类
 */
public class JsonUtil extends JSONUtil{

    // JSON的开闭口字符
    public static final String JSON_ARRAY = "[]";
    public static final String JSONARRAY_BEFORE = "[";
    public static final String JSONARRAY_END = "]";
    public static final String JSONOBJECT_BEFORE = "{";
    public static final String JSONOBJECT_END = "}";

    /**
     * 请求报文排序
     * @param sign
     * @param entry
     * @return
     */
    public static void getSortReqDataStr(StringBuilder sign, Map.Entry entry){
        String key = entry.getKey().toString();
        String value = entry.getValue().toString();
        if (value.startsWith(JSONOBJECT_BEFORE)){
            // 请求参数value为json对象
            sign.append(key.toUpperCase()).append("=");
            sign.append(JSONOBJECT_BEFORE);
            TreeMap<String, String> tempMap = JsonUtil.toBean(value, TreeMap.class, true);
            for (Map.Entry tempEntry : tempMap.entrySet()) {
                if(tempEntry.getValue()!=null){
                    getSortReqDataStr(sign,tempEntry);
                }
            }
            if (sign.length() > 0 && sign.charAt(sign.length() - 1) == '&'){
                sign.deleteCharAt(sign.length() - 1);
            }
            sign.append(JSONOBJECT_END);
            sign.append("&");
        } else if (value.startsWith(JSONARRAY_BEFORE)){
            // 请求参数值为jsonarray
            JSONArray tempArray = parseArray(value);
            if (tempArray.size() > 0 && tempArray.getStr(0).startsWith(JSONOBJECT_BEFORE)){
                sign.append(key.toUpperCase()).append("=");
                sign.append(JSONARRAY_BEFORE);
                for (int i = 0;i < tempArray.size() ;i++){
                    sign.append(getSortArrayStr(tempArray.getStr(i)));
                }
                sign.append(JSONARRAY_END);
                sign.append("&");
            } else {
                sign.append(entry.toString().toUpperCase());
                sign.append("&");
            }
        } else {
            // 拼接赋值
            sign.append(entry.toString().toUpperCase());
            sign.append("&");
        }
    }


    /**
     * json数组结果排序
     * @param jsonStr
     * @return
     */
    private static String getSortArrayStr(String jsonStr){
        StringBuilder sb = new StringBuilder();
        sb.append(JSONOBJECT_BEFORE);
        TreeMap<String, String> tempMap = JsonUtil.toBean(jsonStr, TreeMap.class, true);
        for (Map.Entry tempEntry : tempMap.entrySet()) {
            if(tempEntry.getValue()!=null){
                getSortReqDataStr(sb,tempEntry);
            }
        }
        if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '&'){
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append(JSONOBJECT_END);
        return sb.toString();
    }
}